import { createStore } from 'vuex'
import user from './modules/user'
import chat from './modules/chat'
import merge from 'deepmerge'

/**
 * @return {(store: import('vuex').Store)=>void}
 */
function createPersistPlugin(options = {}) {
    const { key = 'vuex', persistModules } = options
    return (store) => {
        const savedState = JSON.parse(uni.getStorageSync(key) || null)
        if (typeof savedState === 'object' && savedState !== null) {
            store.replaceState(merge(store.state, savedState))
        }
        store.subscribe((mutation, state) => {
            const module = mutation.type.split('/')[0]
            if (persistModules && persistModules.includes(module)) {
                const st = persistModules.reduce((acc, cur) => {
                    acc[cur] = state[cur]
                    return acc
                }, {})
                uni.setStorageSync(key, JSON.stringify(st))
            }
        })
    }
}

const persistPlugin = createPersistPlugin({
    key: 'chatai-plus',
    persistModules: ['user'],
})

export default createStore({
    modules: { chat, user },
    plugins: [persistPlugin],
})
